import { useState, useEffect, Suspense, useRef } from 'react'
import { useParams } from 'react-router-dom'
import { Canvas, useFrame } from '@react-three/fiber'
import { OrbitControls, Stars, Float, Text, useGLTF } from '@react-three/drei'
import { getPublicSpace, getModelFile } from '../api'
import './Space.css'

function Model3D({ url, position, name, description, onClick, isSelected }) {
    const meshRef = useRef()
    const { scene } = useGLTF(url)

    // 旋转动画
    useFrame(() => {
        if (meshRef.current) {
            meshRef.current.rotation.y += 0.005
        }
    })

    return (
        <Float speed={1.5} rotationIntensity={0.5} floatIntensity={0.5}>
            <group position={position}>
                <primitive
                    ref={meshRef}
                    object={scene.clone()}
                    scale={isSelected ? 1.5 : 1}
                    onClick={(e) => {
                        e.stopPropagation()
                        onClick()
                    }}
                />
                <Text
                    position={[0, -1.5, 0]}
                    fontSize={0.3}
                    color="white"
                    anchorX="center"
                    anchorY="middle"
                >
                    {name}
                </Text>
            </group>
        </Float>
    )
}

function Space() {
    const { username } = useParams()
    const [spaceData, setSpaceData] = useState(null)
    const [error, setError] = useState('')
    const [selectedModel, setSelectedModel] = useState(null)

    useEffect(() => {
        loadSpace()
    }, [username])

    const loadSpace = async () => {
        try {
            const res = await getPublicSpace(username)
            setSpaceData(res.data)
        } catch (err) {
            setError(err.response?.data?.error || '加载失败')
        }
    }

    if (error) {
        return (
            <div className="space-error">
                <h1>😢 {error}</h1>
                <a href="/">返回首页</a>
            </div>
        )
    }

    if (!spaceData) {
        return <div className="space-loading">加载中...</div>
    }

    // 过滤出已完成的模型
    const completedModels = spaceData.models.filter(m => m.status === 'completed')

    return (
        <div className="space-container">
            <div className="space-header">
                <h1>🌌 {spaceData.username} 的 3D 空间</h1>
                <p>{completedModels.length} 个模型</p>
            </div>

            <Canvas camera={{ position: [0, 0, 10], fov: 75 }}>
                <color attach="background" args={['#000']} />
                <ambientLight intensity={0.8} />
                <pointLight position={[10, 10, 10]} intensity={1} />
                <pointLight position={[-10, -10, -10]} intensity={0.5} />
                <Stars radius={100} depth={50} count={5000} factor={4} />

                <Suspense fallback={null}>
                    {completedModels.map((model, index) => {
                        const angle = (index / completedModels.length) * Math.PI * 2
                        const radius = 5
                        const x = Math.cos(angle) * radius
                        const z = Math.sin(angle) * radius

                        return (
                            <Model3D
                                key={model.id}
                                url={getModelFile(model.id)}
                                position={[x, 0, z]}
                                name={model.name}
                                description={model.description}
                                onClick={() => setSelectedModel(model)}
                                isSelected={selectedModel?.id === model.id}
                            />
                        )
                    })}
                </Suspense>

                <OrbitControls
                    enablePan={true}
                    enableZoom={true}
                    enableRotate={true}
                    minDistance={3}
                    maxDistance={20}
                />
            </Canvas>

            <div className="space-info">
                <p>🖱️ 拖拽旋转 | 🔍 滚轮缩放 | 👆 点击模型查看详情</p>
            </div>

            {selectedModel && (
                <div className="model-detail-panel">
                    <button
                        className="close-btn"
                        onClick={() => setSelectedModel(null)}
                    >
                        ✕
                    </button>
                    <h2>{selectedModel.name}</h2>
                    <p>{selectedModel.description || '暂无描述'}</p>
                    <div className="model-actions">
                        <a
                            href={getModelFile(selectedModel.id)}
                            download={`${selectedModel.name}.glb`}
                            className="btn-download"
                        >
                            📥 下载模型
                        </a>
                    </div>
                    {selectedModel.comment_count > 0 && (
                        <p className="comment-count">💬 {selectedModel.comment_count} 条留言</p>
                    )}
                </div>
            )}
        </div>
    )
}

export default Space
